package com.vst.pushlib;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import com.baidu.android.pushservice.PushManager;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnLayoutChangeListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

public class PopupScreen {

    public static final String POPSCREEN_ACTION = "com.vst.action.Push.PopupScreen";
    public static final String POPSCREEN_WEIXIN_ACTION = "com.vst.action.Push.PopupScreen.WEIXIN.CHANGED";

    public static final String POPSCREEN_SEMDMSG = "com.vst.action.Push.PopupScreen.SENDMSG";

    private static final int DURATION = 10000;
    private static final int DURATION_MAX = 15000;
    private static final int DURATION_MIN = 8000;

    private Activity mActivity;

    private ViewGroup mParent;

    private int mMessageCount = 0;

    private static final int MAX_MESSAGE_MOVING = 50;

    private Queue<String> mMessageQuene = new LinkedList<String>();

    private List<View> mViews = new ArrayList<View>();

    private HashMap<Integer, TextView> mTextViews = new HashMap<Integer, TextView>();

    private static final int whichLine() {
        return (int) (Math.random() * 4);
    }

    protected String mTag;

    @SuppressLint("NewApi")
    private void move(final int line, final View v, final String msg) {
        if (mActivity == null) {
            return;
        }

        ObjectAnimator anim = ObjectAnimator.ofFloat(v, "x", v.getX(), 0 - v.getWidth());
        anim.setInterpolator(new AccelerateDecelerateInterpolator());

        int duration = (int) (DURATION + (v.getWidth() / (float) sWindowWidth) * DURATION);
        if (mMessageCount > MAX_MESSAGE_MOVING / 2) {
            if (mMessageCount + 10 > MAX_MESSAGE_MOVING) {
                duration = duration - 2000;
            } else {
                duration = duration - 1000;
            }
        }
        if (duration > DURATION_MAX) {
            duration = DURATION_MAX;
        } else if (duration < DURATION_MIN) {
            duration = DURATION_MIN;
        }
        anim.setDuration(duration);
        v.setTag(anim);
        mMessageCount++;
        anim.addListener(new AnimatorListener() {

            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {

                if (mViews != null) {
                    mViews.remove(v);
                }
                if (mParent != null) {
                    mParent.removeView(v);
                }
                mTextViews.remove(line);
                mMessageCount--;
                checkMoving();
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                v.setVisibility(View.INVISIBLE);
                mTextViews.remove(line);
                if (mParent != null) {
                    mParent.removeView(v);
                }
            }
        });
        anim.start();
    }

    private void checkMoving() {
        try {
            String chat = mMessageQuene.poll();
            if (TextUtils.isEmpty(chat)) {
                return;
            }
            if (mMessageCount < MAX_MESSAGE_MOVING) {
                Log.d("jeson2", "showChat");
                show(chat);
            } else {
                mMessageQuene.clear();
                mMessageCount = 0;
                Log.d("jeson2", "can not show");
            }
        } catch (Exception e) {
        }
    }

    PopupWindow mPopupWindow;
    static int sWindowWidth = 0;

    private void show(final String msg) {
        final int line = whichLine();
        TextView lineTextView = mTextViews.get(line);
        if (sWindowWidth == 0) {
            sWindowWidth = mActivity.getWindow().getDecorView().getWidth(); // 1280?
        }
        if (lineTextView != null) {
            if (lineTextView.getX() + lineTextView.getWidth() > sWindowWidth) {
                return;
            } else {
                mTextViews.remove(line);
            }
        }

        DisplayMetrics dm = mActivity.getResources().getDisplayMetrics();
        if (mPopupWindow == null) {
            mParent = new FrameLayout(mActivity);
            mPopupWindow = new PopupWindow(mParent, sWindowWidth * 2, dm.heightPixels / 2);
            mPopupWindow.setFocusable(false);
        }
        mPopupWindow.showAtLocation(mActivity.getWindow().getDecorView(), Gravity.TOP, 0, 0);
        TextView tv = new TextView(mActivity);
        int color = Color.WHITE;
        try {
            JSONObject json = new JSONObject(msg);
            String comment = json.optString("comment");
            if (comment.length() > 30) {
                comment = comment.substring(0, 30) + "...";
            }
            tv.setText(comment);
            color = (int) Long.parseLong(json.optString("font_color", "#FFFFFF").replaceAll("#", "FF"), 16);
        } catch (Exception e) {
            color = Color.WHITE;
        }
        tv.setTextColor(color);
        float radioX = dm.heightPixels / 720f;
        tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30 * radioX);
        tv.setShadowLayer(5 * dm.density, 2 * dm.density, 2 * dm.density, Color.BLACK);
        final FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        tv.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);

        lp.topMargin = (int) (15 * dm.density + line * (tv.getMeasuredHeight() + dm.density * 5));
        lp.leftMargin = sWindowWidth;
        mParent.addView(tv, lp);
        mViews.add(tv);
        mTextViews.put(line, tv);
        tv.addOnLayoutChangeListener(new OnLayoutChangeListener() {

            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop,
                    int oldRight, int oldBottom) {
                move(line, v, msg);
                v.removeOnLayoutChangeListener(this);
            }
        });
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (POPSCREEN_WEIXIN_ACTION.equals(intent.getAction())) {
                sendTag2Wechat(mTag, intent.getStringExtra(PushConstant.EXTRA_MESSAGE));
                return;
            }

            if (POPSCREEN_SEMDMSG.equals(intent.getAction())) {
                sendMsgToUser(intent.getStringExtra("msg"));
                return;
            }
            String msg = intent.getStringExtra(PushConstant.EXTRA_MESSAGE);
            try {
                JSONObject obj = new JSONObject(msg);
                String tag = obj.optString("tag");
                if (!tag.equals(mTag) && !tag.equals("all")) {
                    return;
                }
            } catch (Exception e) {
            }

            mMessageQuene.offer(msg);
            checkMoving();
        }

    };

    private void sendMsgToUser(final String msg) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }

        new Thread(new Runnable() {

            @Override
            public void run() {
                ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("message", msg));
                params.add(new BasicNameValuePair("tag", mTag));
                String ret = PushHandler.doHttp("http://my.91vst.com/wap/chat.php?action=send", params,
                        new Header[] { new BasicHeader("Cookie", "pushkey=" + PushConstant.getBindKey(mActivity)) });
            }

        }).start();
    }

    public void start(Activity activity, String tag) {
        // stop();
        mTag = tag;
        mActivity = activity;
        List<String> tag_list = new ArrayList<String>();
        tag_list.add(tag);
        PushManager.setTags(activity.getApplicationContext(), tag_list);
        sendTag2Wechat(tag, PushConstant.getWeixinId(activity));
        IntentFilter i = new IntentFilter(POPSCREEN_ACTION);
        i.addAction(POPSCREEN_WEIXIN_ACTION);
        i.addAction(POPSCREEN_SEMDMSG);
        mActivity.registerReceiver(mBroadcastReceiver, i);
    }

    public void stop() {
        try {
            if (mActivity != null) {
                sendTag2Wechat("", PushConstant.getWeixinId(mActivity));
                mActivity.unregisterReceiver(mBroadcastReceiver);
            }
            mMessageQuene.clear();
            mMessageCount = 0;

            if (mViews.isEmpty()) {
                return;
            }
            mTextViews.clear();
            for (View v : mViews) {
                // ObjectAnimator anim = (ObjectAnimator) v.getTag();
                // anim.cancel();
                v.clearAnimation();
            }
            mViews.clear();
        } catch (Exception e) {

        }

        if (mPopupWindow != null) {
            mPopupWindow.dismiss();
        }
        mActivity = null;
    }

    private static void sendTag2Wechat(final String tag, final String userid) {
        Log.d("jeson", "tag=" + tag + ",userid=" + userid);
        if (tag == null || TextUtils.isEmpty(userid)) {
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("chat_tag", tag));
                params.add(new BasicNameValuePair("fromUser", userid));
                String ret = PushHandler.doHttp("http://my.91vst.com/weixin/api.php?action=callback_chat", params);
                android.util.Log.e("PopupScreen", "" + ret);
            }

        }).start();
    }
}
